class_name Enemy
extends Area2D

signal hurt(damage)

var data = Global.enemy_data[0]
var cool_down_done = true

var is_move_allow = true

var bullet: PackedScene = preload("res://Scenes/enemy/enemy_attack.tscn")

func _ready() -> void:
	self.hurt.connect(self._hurt)
	if self.is_in_group("enemy") != true:
		self.add_to_group("enemy")

func _on_area_entered(area: Area2D) -> void:
	#检测节点分组
	if area.is_in_group("core"):
		#如果检测到核心，就发射攻击信号
		Global.core_get_damage.emit(data["HIT_ATTACK"])
		self.queue_free()
	elif area.is_in_group("Guardian"):
		Global.core_get_damage.emit(data["HIT_ATTACK"] * area.defend)
		

func _hurt(damage) -> void:
	if data["CURRENT_HP"] - damage <= 0:
		Global.kill_nums += 1
		queue_free()
	else:
		data["CURRENT_HP"] -= damage

func _physics_process(delta: float) -> void:
	var speed = - (self.global_position - Global.core_position).normalized()
	if is_move_allow:
		self.global_position += speed * data["SPEED"] * delta
	if cool_down_done && data["RANGE"] == "TRUE":
		shoot()
		start_cooldown()

func shoot() -> void:
	var b = bullet.instantiate()
	self.get_parent().add_child(b)
	b.global_position = self.global_position
	b._spawn_ready()

func start_cooldown() -> void:
	cool_down_done = false
	await get_tree().create_timer(data["ATTACK_CD"]).timeout
	cool_down_done = true
